package com.qf.data.entity.auth.base;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;

/**
 * 代表用户的基础抽象父类（系统用户、前端用户....）
 */
public interface BaseUser extends UserDetails {

    /**
     * 获取当前用户的信息，返回一个Map集合，Map集合用于生产JWT令牌
     * @return
     */
    Map<String, ?> getUserInfo2Jwt();

    /**
     * 返回用户的来源类型
     * 1 - 系统用户
     * 2 - 微信用户
     * @return
     */
    int getFromType();

    default Map<String, ?> getUserInfoAndFromType2Jwt(){
        Map<String, Object> userInfo = (Map<String, Object>) getUserInfo2Jwt();
        Integer fromType = getFromType();
        userInfo.put("fromType", fromType);
        return userInfo;
    }


    @Override
    default Collection<? extends GrantedAuthority> getAuthorities() {
        return null;
    }

    /**
     * 手动设置权限列表
     * @param collections
     */
    default void setAuthorities(Collection<? extends GrantedAuthority> collections){

    }

    @Override
    default boolean isAccountNonExpired() {
        return true;
    }

    @Override
    default boolean isAccountNonLocked() {
        return true;
    }

    @Override
    default boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    default boolean isEnabled() {
        return true;
    }

    /**
     * 自定义的属性反序列化器
     */
    class GrantedAuthorityDeserialize extends StdDeserializer<SimpleGrantedAuthority> {

        protected GrantedAuthorityDeserialize() {
            super(SimpleGrantedAuthority.class);
        }

        //{"authority":"/RoomPriceManager"}
        @Override
        public SimpleGrantedAuthority deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {

            //获得序列化中的值
            p.nextToken();
            p.currentName();
            p.nextToken();
            String authStr = p.getValueAsString();
            p.nextToken();

            return new SimpleGrantedAuthority(authStr);
        }
    }
}
